const fs = require('fs')
const { parse } = require("csv-parse");
const csv = require('csvtojson')
const axios = require('axios')


/**
 * config start =======================================
 */


/**
 * config end =======================================
 */

const metricsTypeArr_writeMsisdn = ["white", "entity", "write"]


let metricTmp = [
    {
        name: "msisdn_service_call_total",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: ""
            },
            {
                labelName: "serviceCode",
                labelValue: "ENS000001"
            },
            {
                labelName: "serviceEnName",
                labelValue: "NCS"
            },
            {
                labelName: "serviceChName",
                labelValue: "号卡数据管理系统"
            }
        ],
        value: 1000
    },
    {
        name: "msisdn_service_call_success",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: ""
            },
            {
                labelName: "serviceCode",
                labelValue: "ENS000001"
            },
            {
                labelName: "serviceEnName",
                labelValue: "NCS"
            },
            {
                labelName: "serviceChName",
                labelValue: "号卡数据管理系统"
            }
        ],
        value: 998
    },
    {
        name: "msisdn_service_call_fail",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: ""
            },
            {
                labelName: "serviceCode",
                labelValue: "ENS000001"
            },
            {
                labelName: "serviceEnName",
                labelValue: "NCS"
            },
            {
                labelName: "serviceChName",
                labelValue: "号卡数据管理系统"
            }
        ],
        value: 2
    },
    {
        name: "msisdn_service_call_business_fail",
        type: "gauge",
        metricsLabels: [
            {
                labelName: "provinceCode",
                labelValue: "451"
            },
            {
                labelName: "nodeId",
                labelValue: ""
            },
            {
                labelName: "serviceCode",
                labelValue: "ENS000001"
            },
            {
                labelName: "serviceEnName",
                labelValue: "NCS"
            },
            {
                labelName: "serviceChName",
                labelValue: "号卡数据管理系统"
            }
        ],
        value: 1
    },
]

async function readDataFromCsv(filePath) {
    return csv().fromFile(filePath)
        .subscribe(json => {
            return new Promise((resolve, reject) => {
                if (!json) {
                    reject('read csv error')
                } else {
                    resolve(json)
                }
            })
        })
}

let serviceInfoMetricArray = new Array();
let nodeList ;
let serviceList ;

async function sendMetrics_serverInfo(nodeId, provinceCode, year, month, day, hourMinutes) {
    


    nodeList.filter(x => {
        if (!nodeId || nodeId ==='') {
            return true;
        } else {
            return nodeId == x.code;
        }
    })
    .forEach(x => {
        let provArr = x.province.split(',');
        provArr.filter(p => {
            if (!provinceCode || provinceCode == '') {
                return true;
            } else {
                return p == provinceCode;
            }
        })
        .forEach(y => {
            // console.log(x.code, y)
            totalCount += 100;
            totalSuccessCount += 98;
            totalFailCount += 2;
            totalBusinessFailCount += 1;
            serviceList.filter(m => m.parent_id == 0).forEach(m1 => {
                let metricTmpCopy = JSON.parse(JSON.stringify(metricTmp))
                metricTmpCopy.forEach(tmp => {
                    tmp.metricsLabels.forEach(m3 => {
                        if (m3.labelName == 'provinceCode') {
                            m3.labelValue = y;
                        } else if (m3.labelName == 'nodeId') {
                            m3.labelValue = x.code;
                        } else if (m3.labelName == 'serviceCode') {
                            m3.labelValue = m1.code;
                        } else if (m3.labelName == 'serviceEnName') {
                            m3.labelValue = m1.eng_name;
                        } else if (m3.labelName == 'serviceChName') {
                            m3.labelValue = m1.name;
                        } 
                        if (tmp.name == 'msisdn_service_call_total') {
                            tmp.value = totalCount;
                        } else if (tmp.name == 'msisdn_service_call_success') {
                            tmp.value = totalSuccessCount;
                        } else if (tmp.name == 'msisdn_service_call_fail') {
                            tmp.value = totalFailCount;
                        } else if (tmp.name == 'msisdn_service_call_business_fail') {
                            tmp.value = totalBusinessFailCount;
                        }
                    })
                    serviceInfoMetricArray.push(tmp)
                })
            })
        })
    })
    let jsonTmp = JSON.stringify(serviceInfoMetricArray)

    // fs.writeFile("serviceCount.txt", jsonTmp, error => {
    //     if (error) throw error;
    // })
    serviceInfoMetricArray = new Array()
    totalCount = 1000;
    totalSuccessCount = 998;
    totalFailCount = 2;
    totalBusinessFailCount = 2;

    let reportTime = year + month + day + hourMinutes + '00';
    console.log('reportTime: ', reportTime)
    customConfig = {
        headers: {
            'Content-Type': 'application/json',
            'reportTime': reportTime
        }
    };

    console.log(reportTime)

    const resp = await axios.post(REQ_URL, jsonTmp, customConfig);
}





// sendMetrics_serverInfo(nodeId, provinceCode);

function sleep(time) {
    return new Promise((resolve, reject) => {
        return setTimeout(resolve, time);
    });
}

async function batchSendMetricsLoop() {

    nodeList = await readDataFromCsv(__dirname + '/../node-server-info/en_endnode.csv');
    serviceList = await readDataFromCsv(__dirname + '/../node-server-info/en_endnode_svc.csv');

    let hourMinutesList = [
        '0000', '0030', '0100', '0130', '0200',
        '0230', '0300', '0330', '0400', '0430',
        '0500', '0530', '0600', '0630', '0700',
        '0730', '0800', '0830', '0900', '0930',
        '1000', '1030', '1100', '1130', '1200',
        '1230', '1300', '1330', '1400', '1430',
        '1500', '1530', '1600', '1630', '1700',
        '1730', '1800', '1830', '1900', '1930',
        '2000', '2030', '2100', '2130', '2200',
        '2230', '2300', '2330'
      ]
    let days = [31,28,31,30,31,30,31,31,30,31,30,31] 

    let year = 2023;
    ourter:
    for (let i = 1; i <= 12; i++ ) {
        let month = i.toString().padStart(2, '0');
        reportMonth = month;
        let day = days[i - 1];
        for (let j = 1; j <= day; j++) {
            let dayStr = j.toString().padStart(2, '0')
            reportDay = dayStr;
            for (let m = 0; m < hourMinutesList.length; m++) {
                let hourMinute = hourMinutesList[m]
                // console.log(nodeId, provinceCode, year, month, dayStr, hourMinute)
                await sendMetrics_serverInfo(nodeId, provinceCode, year, month, dayStr, hourMinute);
                // break ourter;
            }
            // break ourter;
        }
        // break ourter;
    }
    reportMonth = '';
    reportDay = '';
    
}

function timeSlot (step) {   //  step = 间隔的分钟
    var date = new Date()
    date.setHours(00)    // 时分秒设置从零点开始
    date.setSeconds(00)
    date.setUTCMinutes(00)
    // console.log(date.getHours())
    // console.log(date.getSeconds())
    // console.log(new Date(date.getTime()))
    
    var arr = [], timeArr = [];
    var slotNum = 24*60/step   // 算出多少个间隔
    for (var f = 0; f < slotNum; f++) {   //  stepM * f = 24H*60M
        // arr.push(new Date(Number(date.getTime()) + Number(step*60*1000*f)))   //  标准时间数组
        var time = new Date(Number(date.getTime()) + Number(step*60*1000*f))  // 获取：零点的时间 + 每次递增的时间
        var hour = '', sec = '';
        time.getHours() < 10 ? hour = '0' + time.getHours() : hour = time.getHours()  // 获取小时
        time.getMinutes() < 10 ? sec = '0' + time.getMinutes() : sec = time.getMinutes()   // 获取分钟
        timeArr.push(hour + '' + sec)
    }
    console.log(timeArr)
    return timeArr
}

// 填写具体的端节点ID，为空字符串时代表所有端节点ID
const nodeId = "";
// 填写具体的省份编码，为空字符串代表所有的省份
const provinceCode = "";
const REQ_URL = 'http://15.116.20.124:30061/metrics/report';
// const REQ_URL = 'http://localhost:8080/metrics/report';

let totalCount = 1000;
let totalSuccessCount = 998;
let totalFailCount = 2;
let totalBusinessFailCount = 2;

// batchSendMetricsLoop();

let reportMonth = '';
let reportDay = '';

async function execReport() {
    if (reportMonth === '' && reportDay === '') {
        batchSendMetricsLoop();
        return 'start...'
    } else {
        return 'server count: ' + reportMonth + ", " + reportDay;
    }
}

exports.execReport = execReport;